package com.letv.so.servlet;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.letv.so.bean.AlbumBean;
import com.letv.so.bean.ExtranetAlbumBean;
import com.letv.so.constants.Constants;
import com.letv.so.constants.Mappings;
import com.letv.so.service.QueryDataService;
import com.letv.so.util.NumberUtil;
import com.letv.so.util.StringUtil;

/**
 * http servlet 通用静态方法封装类
 */
public class CommonServlet {

    /**
     * Logger
     */
    private static Logger LOGGER = LoggerFactory.getLogger(CommonServlet.class);

    /**
     * String, 外网站点源cbase key前缀
     */
    private static final String WEBSITE_PREFIX = "newleso_ea_";

    /**
     * String, 内网详情cbase key前缀
     */
    private static final String DETAIL_MMS_PREFIX = "newmms_vrs_a_";

    /**
     * String, 外网详情cbase key增量前缀
     */
    private static final String DETAIL_CMS_INC_PREFIX = "inc";

    /**
     * String, cbase key通用拼接字符
     */
    private static final String COMMON_CBASE_KEY_JOIN_CHARACTER = "_";

    /**
     * String, 通用分割字符
     */
    private static final String COMMON_SPLIT_CHARACTER = ",";

    /**
     * 外网站点源及其简化版接口中调用
     * @param lesoAlbumId String, 作品库album id
     * @param websiteIdList String, source映射id由,拼接而成的字符串
     * @return List<String>, cbase中外网站点源key组成的列表。为空或出错则返回空列表
     */
    static List<String> getWebsiteSokeyList(String lesoAlbumId, String websiteIdList) {
        List<String> result = new ArrayList<String>();
        if(StringUtils.isBlank(lesoAlbumId)) {
            return result;
        }
        try {
            if(StringUtils.isBlank(websiteIdList)) {
                for (String source : Mappings.WEBSITE_LIST) {
                    result.add(CommonServlet.WEBSITE_PREFIX + lesoAlbumId + CommonServlet.COMMON_CBASE_KEY_JOIN_CHARACTER + source);
                }
            } else {
                String[] websiteIdArray = websiteIdList.split(CommonServlet.COMMON_SPLIT_CHARACTER);
                for(int i = 0; i < websiteIdArray.length; i++) {
                    if(StringUtils.isBlank(websiteIdArray[i])) {
                        continue;
                    }
                    String targetSource = Constants.WEBSITE_ID_MAP.get(websiteIdArray[i]);
                    if(StringUtils.isBlank(targetSource)) {
                        continue;
                    }
                    result.add(CommonServlet.WEBSITE_PREFIX + lesoAlbumId + CommonServlet.COMMON_CBASE_KEY_JOIN_CHARACTER + targetSource);
                }
            }            
        } catch(Exception e) {
            LOGGER.error("method getWebsiteSokeyList catch errors", e);
            result = new ArrayList<String>();
        }
        return result;
    }

    /**
     * 外网站点源及其简化版接口中调用
     * @param ifTarget boolean, true--指定展现列表, false--未指定展现列表
     * @param extranetAlbumBean ExtranetAlbumBean, 外网album。当ifTarget==true时，默认本参数在指定展现的列表中。
     * @param ifTvRequest boolean, true--tv端请求, false--非tv端请求
     * @return boolean, true--针对传入请求方展现传入album, false--针对传入请求方不展现传入album
     */
    static boolean websiteIfOn(boolean ifTarget, ExtranetAlbumBean extranetAlbumBean, boolean ifTvRequest) {
        if(null == extranetAlbumBean) {
            return false;
        }
        boolean result = true;
        try {
            if(ifTarget) {
                return result;
            }
         // TODO 待刷新完芒果播控后再放开对芒果的判断
//            String pushflag = StringUtils.isBlank(extranetAlbumBean.getPushflag()) ? "" : extranetAlbumBean.getPushflag();
//            String pushflagExceptTv = StringUtils.isBlank(pushflag) ? "" : pushflag.replace(Constants.PUSHFLAG_TV, "").replace(CommonServlet.COMMON_SPLIT_CHARACTER, "");
            String isCibnChecked = StringUtils.isBlank(extranetAlbumBean.getIs_cibn_checked()) ? "" : extranetAlbumBean.getIs_cibn_checked();
            String source = StringUtils.isBlank(extranetAlbumBean.getSite()) ? "" : extranetAlbumBean.getSite();
            if(ifTvRequest) {
             // TODO 待刷新完芒果播控后再放开对芒果的判断
//                if("0".equals(isCibnChecked) || pushflag.indexOf(Constants.PUSHFLAG_TV) < 0) {
                if("0".equals(isCibnChecked)) {
                    result = false;
                }
            } else {
                // TODO 待刷新完芒果播控后再放开对芒果的判断
//                if(Constants.WEBSITE_CIBN.equals(source) || Constants.WEBSITE_WASUTV.equals(source) || (Constants.WEBSITE_IMGO.equals(source) && StringUtils.isBlank(pushflagExceptTv))) {
                if(Constants.WEBSITE_CIBN.equals(source) || Constants.WEBSITE_WASUTV.equals(source)) {
                    result = false;
                }
            }
        } catch(Exception e) {
            LOGGER.error("method ifOn catch errors", e);
            result = false;
        }
        return result;
    }

    /**
     * 外网站点源及其简化版接口中调用：外网站点源排序
     * @param ifTarget boolean, true--指定展现列表, false--未指定展现列表
     * @param extranetAlbumBeanList, List<ExtranetAlbumBean>, 待排序外网专辑列表
     */
    static void websiteSort(boolean ifTarget, List<ExtranetAlbumBean> extranetAlbumBeanList) {
        if(null == extranetAlbumBeanList || extranetAlbumBeanList.size() == 0) {
            return;
        }
        try {
            if(ifTarget) {
                return;
            }
            Collections.sort(extranetAlbumBeanList, new WebsiteComparator());
        } catch(Exception e) {
            LOGGER.error("method websiteSort catch errors", e);
        }
    }

    static AlbumBean getDetailAlbum(QueryDataService queryDataService, String cbaseKey, String timestamp, String cbaseDefaultData, boolean ifTvRequest, String websiteIdList) {
        if(null == queryDataService || StringUtils.isBlank(timestamp) || StringUtils.isBlank(cbaseKey)) {
            return null;
        }
        AlbumBean result = null;
        try {
            // 媒资专辑
            if(cbaseKey.contains(CommonServlet.DETAIL_MMS_PREFIX)) {
                if(StringUtils.isBlank(cbaseDefaultData)) {
                    return null;
                }
                return JSON.parseObject(cbaseDefaultData, AlbumBean.class);
            }

            // 外网专辑：指定站源展示序列
            if(!StringUtils.isBlank(websiteIdList)) {
                String[] websiteIdArray = websiteIdList.split(CommonServlet.COMMON_SPLIT_CHARACTER);
                String targetSource = null;
                for(int i = 0; i < websiteIdArray.length; i++) {
                    if(StringUtils.isBlank(websiteIdArray[i])) {
                        continue;
                    }
                    targetSource = Constants.WEBSITE_ID_MAP.get(websiteIdArray[i]);
                    break;
                }
                if(StringUtils.isBlank(targetSource)) {
                    return null;
                }
                if(!StringUtils.isBlank(cbaseDefaultData)) {
                    AlbumBean albumBean = JSON.parseObject(cbaseDefaultData, AlbumBean.class);
                    if(targetSource.equals(albumBean.getSubSrc())) {
                        return albumBean;
                    }
                }
                String targetAlbumStr = queryDataService.get(timestamp, CommonServlet.DETAIL_CMS_INC_PREFIX + cbaseKey + CommonServlet.COMMON_CBASE_KEY_JOIN_CHARACTER + targetSource);
                if(StringUtil.isBlank(targetAlbumStr)) {
                    targetAlbumStr = queryDataService.get(timestamp, cbaseKey + CommonServlet.COMMON_CBASE_KEY_JOIN_CHARACTER + targetSource);
                }
                if(StringUtil.isBlank(targetAlbumStr)) {
                    return null;
                }
                return JSON.parseObject(targetAlbumStr, AlbumBean.class);
            }

            // 外网专辑：未指定站源展示序列
            AlbumBean albumBean = null;
            String source = "";
            String is_cibn_show = "";
            // TODO 待刷新完芒果播控后再放开对芒果的判断
//            String pushflagExceptTv = "";
            if(!StringUtils.isBlank(cbaseDefaultData)) {
                albumBean = JSON.parseObject(cbaseDefaultData, AlbumBean.class);
                source = StringUtils.isBlank(albumBean.getSubSrc()) ? "" : albumBean.getSubSrc();
                is_cibn_show = StringUtils.isBlank(albumBean.getIs_cibn_show()) ? "" : albumBean.getIs_cibn_show();
                // TODO 待刷新完芒果播控后再放开对芒果的判断
//                pushflagExceptTv = StringUtils.isBlank(albumBean.getPushFlag()) ? "" : albumBean.getPushFlag().replace(Constants.PUSHFLAG_TV, "").replace(CommonServlet.COMMON_SPLIT_CHARACTER, "");
            }
            if(ifTvRequest) {
                if(null != albumBean && "1".equals(is_cibn_show)) {
                    result = albumBean;
                }
                for(String tvLicenseSource : Constants.TV_LICENSE_SOURCE_LIST) {
                    String tempCbaseData = queryDataService.get(timestamp, CommonServlet.DETAIL_CMS_INC_PREFIX + cbaseKey + CommonServlet.COMMON_CBASE_KEY_JOIN_CHARACTER + tvLicenseSource);
                    if(StringUtil.isBlank(tempCbaseData)) {
                        tempCbaseData = queryDataService.get(timestamp, cbaseKey + CommonServlet.COMMON_CBASE_KEY_JOIN_CHARACTER + tvLicenseSource);
                    }
                    if(StringUtil.isBlank(tempCbaseData)) {
                        continue;
                    }
                    AlbumBean tempAlbumBean = JSON.parseObject(tempCbaseData, AlbumBean.class);
                    if("1".equals(tempAlbumBean.getIs_cibn_show())) {
                        result = tempAlbumBean;
                        break;
                    }
                }
            } else {
                if(null == albumBean) {
                    return null;
                }
                // TODO 待刷新完芒果播控后再放开对芒果的判断
                if(Constants.WEBSITE_CIBN.equals(source) || Constants.WEBSITE_WASUTV.equals(source)) {
//                if(Constants.WEBSITE_CIBN.equals(source) || Constants.WEBSITE_WASUTV.equals(source) || (Constants.WEBSITE_IMGO.equals(source) && StringUtils.isBlank(pushflagExceptTv))) {
                    return null;
                }
                result = albumBean;
            }
        } catch(Exception e) {
            LOGGER.error("method getDetailAlbum catch errors,sid=" + timestamp);
            result = null;
        }
        return result;
    }
}

class WebsiteComparator implements Comparator<ExtranetAlbumBean> {
    public int compare(ExtranetAlbumBean extranetAlbumBean1, ExtranetAlbumBean extranetAlbumBean2) {
        return new Integer(NumberUtil.getInt(extranetAlbumBean1.getTophot(), Integer.MAX_VALUE)).compareTo(NumberUtil.getInt(extranetAlbumBean2.getTophot(), Integer.MAX_VALUE));
    }
}
